package com.wu.springboot_study.controller;

import cn.hutool.core.util.RandomUtil;
import com.wu.springboot_study.entity.User;
import com.wu.springboot_study.service.IUserService;
import com.wu.springboot_study.util.JedisUtil;
import lombok.AllArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;

/**
 * @author benjamin_5
 * @Description
 * @date 2023/1/9
 */
@RestController
@RequestMapping("redission")
@AllArgsConstructor
public class RedissionController {

    private final IUserService userService;
    private final RedissonClient redissonClient;
    private final JedisUtil jedisUtil;

    @GetMapping("set")
    public User set(String key,String value){
        // 解决缓存穿透
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter("userBloom");
        if(bloomFilter.contains(key)){
            // 解决缓存击穿
            User user = jedisUtil.get(key);
            if(user == null){
                 user = userService.getById(key);
                jedisUtil.set(key, user);
                // 解决缓存雪崩
                int expireTime = RandomUtil.getRandom().nextInt(100); // 范围内随机值
                jedisUtil.expire(key, expireTime);
            }
            return user;
        }
        return null;
    }

}
